package com.example.yrdev.ordering_system.Utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

//import net.sourceforge.pinyin4j.PinyinHelper;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

/**
 * Created by yrdev on 7/18/16.
 */
public class GlobalFunction {
    public static ProgressDialog dialog;
    private static final String lanKey="lan_key";
    public static Context context;

    public static void printText(String tag, String content){
        Log.d(tag,content);

    }

    public static void printTextByTag(String content){
        Log.d("tags",content);

    }

    public static void showProgress(Context context, String title, String body){
        if (GlobalFunction.dialog==null){
            GlobalFunction.dialog= ProgressDialog.show(context,title,body);

        }else {
            GlobalFunction.dialog.show();
        }
    }

    public static void showProgress(Context context, String body){
       showProgress(context,"提示",body);
    }


   public static String getMyUUID(Activity activity){
        final TelephonyManager tm = (TelephonyManager) activity.getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();

        androidId = "" + android.provider.Settings.Secure.getString(activity.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        Log.d("debug","uuid="+uniqueId);
        return uniqueId;
    }

    public static void  dismissProgress(){
        if (GlobalFunction.dialog!=null){
            GlobalFunction.dialog.dismiss();
            GlobalFunction.dialog=null;
            
        }
    }
    public static Integer convertToInt(Double value){
        String string=String.valueOf(value);
        //String str = string.substring(0, string.indexOf(".")) + string.substring(string.indexOf(".") + 1);
        //int intgeo = Integer.parseInt(str);
        double num;
        long iPart;
        double fPart;

// Get user input
        num = value;

        iPart = (long) num;
        fPart = num - iPart;

      String fractioNalPart=  String.valueOf(fPart).replace("0.","");

        GlobalFunction.printTextByTag(fractioNalPart);

        return (int)Double.parseDouble(string);





    }
    public  static String convertDate(Date date,String format){

        DateFormat df = new SimpleDateFormat(format,Locale.getDefault());



        return df.format(date);



    }


    public static boolean isTimeBetweenTwoTime(String argStartTime, String argEndTime) throws ParseException {
boolean stat=false;

        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        //
        if (argStartTime.matches(reg) && argEndTime.matches(reg)) {
            boolean valid = false;
            // Start Time
            java.util.Date startTime = new SimpleDateFormat("HH:mm:ss",Locale.getDefault())
                    .parse(argStartTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);

            // Current Time
            java.util.Date currentTime = new SimpleDateFormat("HH:mm",Locale.getDefault())
                    .parse(GlobalFunction.getCurrentHourMin());
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentTime);

            // End Time
            java.util.Date endTime = new SimpleDateFormat("HH:mm:ss",Locale.getDefault())
                    .parse(argEndTime);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);

            //
            if (currentTime.compareTo(endTime) < 0) {

                currentCalendar.add(Calendar.DATE, 1);
                currentTime = currentCalendar.getTime();

            }

            if (startTime.compareTo(endTime) < 0) {

                startCalendar.add(Calendar.DATE, 1);
                startTime = startCalendar.getTime();

            }
            //
            if (currentTime.before(startTime)) {

                System.out.println(" Time is Lesser ");

                valid = false;
            } else {

                if (currentTime.after(endTime)) {
                    endCalendar.add(Calendar.DATE, 1);
                    endTime = endCalendar.getTime();

                }

                System.out.println("Comparing , Start Time /n " + startTime);
                System.out.println("Comparing , End Time /n " + endTime);
                System.out
                        .println("Comparing , Current Time /n " + currentTime);

                if (currentTime.before(endTime)) {
                    System.out.println("RESULT, Time lies b/w");
                    valid = true;
                } else {
                    valid = false;
                    System.out.println("RESULT, Time does not lies b/w");
                }

            }
            return valid;

        } else {
            throw new IllegalArgumentException(
                    "Not a valid time, expecting HH:MM:SS format");
        }



    }



    public static Double convertToDouble(Integer value){


        return (double)value;


    }


    public static String getSerialNumber(){

        String serial = null;
         String android_id =  Settings.Secure.getString(context.getContentResolver(),
                 Settings.Secure.ANDROID_ID);



        return android_id.toUpperCase();


    }

    public static   void initLanguage(Context context){

        Locale myLocale= new Locale(GlobalFunction.getCurrentLanKey(context));
        Resources res=context.getResources();
        DisplayMetrics dm=res.getDisplayMetrics();
        Configuration configuration=res.getConfiguration();
        configuration.locale=myLocale;
        res.updateConfiguration(configuration,dm);


    }
    public static String getResourceString(Context context, int key){
        return context.getResources().getString(key);

    }


    public static String getCurrentLanKey(Context context){

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

        return settings.getString(GlobalFunction.lanKey, Locale.getDefault().getLanguage());

    }

    public static void setLanKey(Context context, String key){

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

        SharedPreferences.Editor editor = settings.edit();
        editor.putString(GlobalFunction.lanKey,key ).apply();

    }


    public static void showKeyboardForEditText(Context context, EditText editText){
        InputMethodManager imm = (InputMethodManager)context. getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
    public static int convertToInt(String value){
        return Integer.valueOf(value);

    }
    public static void ToastAlert(Context context, String alert){
        Toast.makeText(context,alert, Toast.LENGTH_SHORT).show();
    }

    public  static  int converToPx(Context context, int dp){
    Resources r = context.getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    return (int)px;

    }

    public  static String getCurrentDateTime(){

            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault());
            Date date = new Date();
            return dateFormat.format(date);

    }

    public  static String httpLatestReqTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }
    public static String checkedPriceText(Double price){

        return String.format(Locale.getDefault(),"%.2f",price);

    }
   public  static String goodRequestHttpTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getCurrentDate(){

        DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getCurrentTime(){

        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getCurrentHourMin(){

        DateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public static String getOnlyID(Context context){

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        String ts = String.valueOf( System.currentTimeMillis());


        return ts+tm.getDeviceId().substring(0,4);


    }
    public  static void playMusicFile(Context context,String file){
        try {
            int resID=context.getResources().getIdentifier(file, "raw", context. getPackageName());
            MediaPlayer mediaPlayer=MediaPlayer.create(context,resID);

            mediaPlayer.start();

        }catch (Exception e){

            e.printStackTrace();
        }



    }


    private String convertToHexString(int x){

        System.out.println(x + "的十六进制结果是：" + Integer.toHexString(x));
        String hexString= Integer.toHexString(x);
        return hexString;

    }
    public static ArrayList<String> getConvertedName(String name){

        ArrayList<String>arrayList=new ArrayList<>();
        if (!arrayList.contains(name)){

            arrayList.add(name);
        }

        char[] tempArr=name.toCharArray();

        for (char splitted:tempArr){

            String[]converted= new String[]{};


            //PinyinHelper.toHanyuPinyinStringArray(splitted);

            if (converted!=null && converted[0].length()>0){

                if (!arrayList.contains(converted[0])){
                    arrayList.add(converted[0]);
                }
            }
        }



        return arrayList;

    }
//    public static ArrayList<String> getConvertedName(String name){
//
//        ArrayList<String> arrayList=new ArrayList<>();
//        if (!arrayList.contains(name)){
//
//            arrayList.add(name);
//        }
//
//        char[] tempArr=name.toCharArray();
//
//        for (char splitted:tempArr){
//
//            String[]converted= PinyinHelper.toHanyuPinyinStringArray(splitted);
//
//            if (converted!=null && converted[0].length()>0){
//
//                if (!arrayList.contains(converted[0])){
//                    arrayList.add(converted[0]);
//                }
//            }
//        }
//
//
//
//        return arrayList;
//
//    }

}
